package com.yantong.service.impl;

import com.yantong.exception.BDException;
import com.yantong.result.ResultVo;
import com.yantong.utils.PageUtils;
import com.yantong.pojo.AssetConfig;
import com.yantong.service.ConfigService;
import com.yantong.pojo.Member;
import com.yantong.pojo.MemberWallet;
import com.yantong.pojo.MemberWalletLog;
import com.yantong.enums.WalletLogOperationTypeEnum;
import com.yantong.enums.WalletLogTypeEnum;
import com.yantong.mapper.MemberMapper;
import com.yantong.mapper.MemberWalletMapper;
import com.yantong.service.MemberService;
import com.yantong.service.MemberWalletService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liaozhaogui
 * @description: MemberWalletServiceImpl
 * @date 2020/9/22 17:20
 */
@Service
public class MemberWalletServiceImpl implements MemberWalletService {
	@Autowired
	private MemberWalletMapper memberWalletMapper;
	@Autowired
	private ConfigService configService;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private MemberService memberService;


	@Override
	public MemberWallet findById(Member member) {
		MemberWallet memberWallet = memberWalletMapper.findById(member.getId());
		if (null == memberWallet) {
			memberWallet = new MemberWallet();
			memberWallet.setEADD(this.generatedNumber(member.getCreatetime()));
			memberWallet.setMemberId(member.getId());
			memberWallet.setAA(BigDecimal.ZERO);
			memberWallet.setACA(BigDecimal.ZERO);
			memberWallet.setAQ(BigDecimal.ZERO);
			memberWallet.setBanBPay(BigDecimal.ZERO);
			memberWallet.setAD(BigDecimal.ZERO);
			this.insert(memberWallet);
		}
		AssetConfig assetConfig = configService.getAssetConfig(member.getCentreId());
		if (null != assetConfig) {
			memberWallet.setICTI(assetConfig.getICTI());
			memberWallet.setDQ(assetConfig.getDQ());
			memberWallet.setDT(assetConfig.getDT());
			memberWallet.setTV(assetConfig.getTV());
		}
		return memberWallet;
	}

	@Override
	public List<MemberWallet> queryAll() {
		return memberWalletMapper.queryAll();
	}

	@Override
	public Long insert(MemberWallet memberWallet) {
		return memberWalletMapper.insert(memberWallet);
	}

	@Override
	public int update(MemberWallet memberWallet) {
		return memberWalletMapper.update(memberWallet);
	}

	@Override
	public void updateBanBPay(Long memberId, String EADD, BigDecimal money) {
		//查询转赠人钱包信息
		MemberWallet memberWallet = memberWalletMapper.findById(memberId);
		if (memberWallet.getBanBPay().compareTo(money) < 0) {
			throw new BDException("余额不足，无法转出");
		}
		MemberWallet memberWalletEADD = memberWalletMapper.findByEADD(EADD);
		if (memberWalletEADD == null) {
			throw new BDException("钱包地址有误，请核实后重新转赠");
		}
		if (EADD.equals(memberWallet.getEADD())) {
			throw new BDException("不能转给自己");
		}
		MemberWallet memberWalletParam = new MemberWallet();
		memberWalletParam.setMemberId(memberId);
		memberWalletParam.setBanBPay(memberWallet.getBanBPay().subtract(money));
		memberWalletMapper.update(memberWalletParam);

		memberWalletMapper.insertLog(new MemberWalletLog(memberWallet.getEADD(), memberWallet.getMemberId(), WalletLogTypeEnum.BanBPay.getCode(),
				WalletLogOperationTypeEnum.EXPENDITURE.getCode(), money, 100d));

		memberWalletParam = new MemberWallet();
		memberWalletParam.setMemberId(memberWalletEADD.getMemberId());
		memberWalletParam.setBanBPay(memberWalletEADD.getBanBPay().add(money));
		memberWalletMapper.update(memberWalletParam);

		memberWalletMapper.insertLog(new MemberWalletLog(memberWalletEADD.getEADD(), memberWalletEADD.getMemberId(), WalletLogTypeEnum.BanBPay.getCode(),
				WalletLogOperationTypeEnum.INCOME.getCode(), money, 100d));
	}

	private String generatedNumber(Date date) {
		long time = date.getTime() / 1000;
		return "ZBKJ" + time + "BB";
	}

	@Override
	public Long insertLog(MemberWalletLog memberWalletLog) {
		return memberWalletMapper.insertLog(memberWalletLog);
	}

	@Override
	public PageUtils<MemberWalletLog> findLog(Long mid, Integer type, int offset, int limit) {
		PageUtils<MemberWalletLog> pageUtils = new PageUtils<>();
		Map<String, Object> params = new HashMap<>(16);
		params.put("memberId", mid);
		params.put("type", type);

		int total = memberWalletMapper.countTotal(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(memberWalletMapper.findLogList(params, new RowBounds(offset, limit)));
		}

		return pageUtils;
	}

	@Override
	public ResultVo redenvelopeTurnout(BigDecimal money, Long mid) {
		ResultVo resultVo = new ResultVo();
		if(mid==null){
			throw new BDException("用户为空");
		}
		try {
			Member member = memberService.getByKey(mid);
			BigDecimal redenvelopeMoney = member.getRedenvelope();
			//判断用户红包余额是否为空
			if(redenvelopeMoney.equals("")||redenvelopeMoney.equals(null)){
				resultVo.put("msg", "用户红包余额为空");
				resultVo.put("code", -1);
				return resultVo;
			}
            //如果转入金额为负数
			if(money.compareTo(BigDecimal.ZERO) == -1){
				resultVo.put("msg", "请输入正确的转入金额");
				resultVo.put("code", -1);
				return resultVo;
			}
			//如果转入金额为0
			if(money.compareTo(BigDecimal.ZERO) == 0){
				resultVo.put("msg", "请输入正确的转入金额");
				resultVo.put("code", -1);
				return resultVo;
			}
			//如果提取金额大于红包余额
			if(money.compareTo(redenvelopeMoney) == 1){
				resultVo.put("msg", "转入金额不能大于红包余额");
				resultVo.put("code", -1);
				return resultVo;
			}
			//如果提取金额小于或者等于红包余额
			if(money.compareTo(redenvelopeMoney) < 1){
				//获取用户电子钱包
				MemberWallet memberWallet = memberWalletMapper.findById(member.getId());
				if(memberWallet==null){
					resultVo.put("msg", "请关注”众邦制造“小程序，建立自己的电子钱包账户");
					resultVo.put("code", -1);
					return resultVo;
				}else{
					//获取电子钱包资产
					BigDecimal aa = memberWallet.getAA();
					//将转入金额存入资产
					memberWallet.setAA(aa.add(money));
                    //将红包余额减去转入金额
					member.setRedenvelope(redenvelopeMoney.subtract(money));
                    //插入电子钱包操作日志
					insertLog(new MemberWalletLog(memberWallet.getEADD(), memberWallet.getMemberId(), WalletLogTypeEnum.Redenvelope.getCode(),
							WalletLogOperationTypeEnum.INCOME.getCode(), money, null));
					//更新红包余额
                    memberMapper.updateRedENvelopeByMid(member);
                    //更新电子钱包
					memberWalletMapper.update(memberWallet);
					resultVo.put("success", true);
					return resultVo;
				}
			}

		}catch (Exception e){
			e.printStackTrace();
		}
		return resultVo;
	}

}
